<template>
    <div>
        <!-- 功能区域 -->
        <el-form :inline="true" :model="parameters" class="demo-form-inline">
            <el-form-item>
                <el-input v-model="parameters.name" placeholder="角色名字" @keyup.enter.native="queryName()"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="info" @click="queryName()">查询</el-button>
                <el-button type="primary" @click="addDialogForm = true">新增</el-button>
            </el-form-item>
        </el-form>

        <!-- 数据区域 -->
        <el-table
            :data="tableData"
            border
            style="width: 100%">
            <el-table-column
            prop="id"
            label="ID"
            width="79" align="center">
            </el-table-column>
            <el-table-column
            prop="roleName"
            label="角色名字">
            </el-table-column>
            <el-table-column
            prop="code"
            label="角色编码">
            </el-table-column>
            <el-table-column
            prop="info"
            label="角色信息">
            </el-table-column>
            <el-table-column
            prop="operation"
            label="操作">
                <template slot-scope="scope">
                    <el-button type="text" @click="setCheckedKeys(scope.row.id)">分配权限</el-button>
                    <el-divider direction="vertical"></el-divider>
                    <el-button type="text" @click="dialogFormVisible = true, getRoleInfo(scope.row.id)">编辑</el-button>
                    <el-divider direction="vertical"></el-divider>
                    <el-button type="text" @click="delRole(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            @size-change="currentSize"
            @current-change="currPage"
            :pager-count="5"
            :page-size="parameters.pageSize"
            :page-sizes="[5, 10, 15]"
            :current-page="parameters.currentPage"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>

        <el-dialog title="编辑" :visible.sync="dialogFormVisible" :append-to-body="true" :close-on-click-modal="false" width="500px">
            <el-form :model="form" :rules="rules" ref="form">
                <el-form-item label="角色名字" :label-width="formLabelWidth" prop="roleName">
                    <el-input v-model="form.roleName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="角色编码" :label-width="formLabelWidth" prop="code">
                    <el-input v-model="form.code" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="角色信息" :label-width="formLabelWidth">
                    <el-input v-model="form.info" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateRole()">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="新增" :visible.sync="addDialogForm" :append-to-body="true" :close-on-click-modal="false" width="500px">
            <el-form :model="addForm" :rules="rules" ref="addForm">
                <el-form-item label="角色名字" :label-width="formLabelWidth" prop="roleName">
                    <el-input v-model="addForm.roleName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="角色编码" :label-width="formLabelWidth" prop="code">
                    <el-input v-model="addForm.code" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="角色信息" :label-width="formLabelWidth">
                    <el-input v-model="addForm.info" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addDialogForm = false">取 消</el-button>
                <el-button type="primary" @click="addRole()">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="分配权限" :visible.sync="permsDialogForm" :append-to-body="true" :close-on-click-modal="false" width="500px">
            <el-form :model="treeForm">
                <el-tree
                    :data="treeData"
                    show-checkbox
                    ref="tree"
                    node-key="id"
                    :check-strictly=open
                    :default-expand-all="true"
                    :props="defaultProps"
                    @check="handleCheck">
                </el-tree>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="permsDialogForm = false">取 消</el-button>
                <el-button type="primary" @click="updatePerms('treeForm')">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            tableData: [{
                id: '',
                roleName: '',
                code: '',
                info: ''
            }],
            
            dialogFormVisible: false,
            addDialogForm: false,
            permsDialogForm: false,

            addForm: {
                roleName: '',
                code: '',
                info: ''
            },

            form: {
                id: '',
                roleName: '',
                code: '',
                info: ''
            },
            formLabelWidth: '80px',
            rules: {
                roleName: [
                    { required: true, message: '名字不能为空', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '编码不能为空', trigger: 'blur' }
                ]
            },

            total: 0,
            parameters: {
                name: '',
                currentPage: 1,
                pageSize: 5
            },

            treeData: [],

            defaultProps: {
                children: 'child',
                label: 'name'
            },

            open: true,
            treeForm: {},
            menuIds: []
        }
    },
    methods: {
        getRoleList() {
            this.$axios.post('role/list', this.parameters).then(response => {
                this.tableData = response.data.data.roleList
                this.total = response.data.data.total
            })
        },
        getRoleInfo(id) {
            this.$axios.post('role/roleInfo', id).then(response => {
                if (response.data.code === 200) {
                    this.form = response.data.data
                } else {
                    this.$message.error(response.data.message);
                }
            })
        },
        updateRole() {
            this.$refs.form.validate(valid => {
                if (!valid) return
                this.$axios.post('role/update', this.form).then(response => {
                    if (response.data.code === 200) {
                        this.dialogFormVisible = false
                        this.$message.success(response.data.message)   
                        this.getRoleList()
                    } else {
                        this.$message.error(response.data.message);
                    }
                })
            })
        },
        delRole(id) {
            this.$confirm('确定删除该角色?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.post('role/delRole', id).then(response => {
                    if (response.data.code === 200) {
                        this.$message.success(response.data.message)
                        this.getRoleList()
                    } else {
                        this.$message.error(response.data.message)
                    }
                })
            }).catch(() => {});
        },
        queryName() {
            this.getRoleList()
        },
        currentSize(newSize) {
            this.parameters.pageSize = newSize
            this.getRoleList()
        },
        currPage(newPage) {
            this.parameters.currentPage = newPage
            this.getRoleList()
        },
        addRole() {
            this.$refs.addForm.validate(valid => {
                if (!valid) return
                this.$axios.post('role/addRole' ,this.addForm).then(response => {
                    if(response.data.code === 200) {
                        this.$message.success(response.data.message)
                        this.addDialogForm = false
                        this.getRoleList()
                    } else {
                        this.$message.error(response.data.message)
                    }
                })
            })
        },
        getTreeList() {
            this.$axios.get('menu/treeList').then(response => {
                this.treeData = response.data.data
            })
        },
        setCheckedKeys(id) {
            this.permsDialogForm = true
            this.$axios.get('menu/menuIdList/' + id).then(response => {
                if (response.data.code === 200) {
                    this.open = true
                    this.$refs.tree.setCheckedKeys(response.data.data.menuList)
                    this.open = false
                    this.treeForm = response.data.data
                    this.treeForm.uid = id
                }
            })
        },
        updatePerms(formName) {
            // let menuIdList = []
            // menuIdList = this.menuIds
            if (this.treeForm.id !== 1) {
                this.$axios.post('role/updatePerms/' + this.treeForm.id, this.menuIds).then(response => {
                    if (response.data.code === 200) {
                        this.permsDialogForm = false
                        this.$message.success('分配成功')
                        if (response.data.data) {
                            let timer = setTimeout(() => {
                                //需要定时执行的代码
                                this.loginOut()
                                this.$message.warning('限权发生变化,请重新登录')
                            },2000)
                        }
                    } else {
                        this.$message.error(response.data.data.message)
                    }
                })
            } else {
                this.permsDialogForm = false
                this.$message.error('管理员禁止修改')
            }
        },
        handleCheck(data, checkedData) {
            // this.$refs.tree.setCheckedKeys(newMenuIds)
            let zi = this.$refs.tree.getCheckedKeys()//返回选中子节点的key
            let fu = this.$refs.tree.getHalfCheckedKeys()//返回选中子节点的父节点的key
            this.menuIds = zi.concat(fu)
        },
        loginOut() {
            this.$axios.get('user/logout').then(response => {
                if (response.data.code === 200) {
                    window.localStorage.removeItem('token')
                    window.sessionStorage.removeItem('userInfo')
                    this.$router.push('/login')
                }
            })
        }
    },
    created() {
        this.getRoleList()
        this.getTreeList()
    }
}
</script>

<style>
.el-table__header tr,
.el-table__header th {
    padding: 0;
    height: 30px;
    line-height: 30px;
}
.el-table__body tr,
.el-table__body td {
    padding: 0;
    height: 30px;
    line-height: 30px;
}

.el-dialog__header {
    text-align: center;
}

.demo-form-inline {
    float: left;
    height: 50px;
    margin-bottom: 10px;
}

.el-pagination {
    float: right;
    margin-top: 15px;
}

.el-pagination__jump {
    margin-left: 5px;
}

.el-pagination .btn-prev,
.el-pagination .btn-next,
.el-pagination button:disabled,
.el-pager li,
.el-pager li.active {
    background-color: #ECECED !important;
}
</style>